/**
 * 
 */
package cn.ivicar.app.controller;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;

import cn.com.carsmart.exception.BadRequestException;
import cn.com.carsmart.exception.CarsmartException;
import cn.com.carsmart.ws.model.SimChargeRecord;
import cn.com.carsmart.ws.model.SimFlowPackageInfo;
import cn.ivicar.sim.service.SimChargeRecordService;
import cn.ivicar.sim.service.SimService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @author liurunbin 2017年6月22日 cn.ivicar.app.controller
 */
public class OrderController {

	private static transient final Logger LOGGER = LoggerFactory.getLogger(OrderController.class);

	@Inject
	private SimChargeRecordService simChargeRecordService;
	@Inject
	private SimService simService;

	public JSONObject getOrderList(Long customerId, Integer pageIndex, Integer pageSize) throws CarsmartException {
		JSONObject result = new JSONObject();
		JSONArray items = new JSONArray();
		if (pageIndex == null) {
			pageIndex = 0;
		}

		if (pageSize == null) {
			pageSize = 10;
		}

		List<SimChargeRecord> list = simChargeRecordService.getList(customerId, pageIndex, pageSize);
		if (list != null) {
			for (SimChargeRecord record : list) {
				items.add(SimChargeRecordToJSON(record));
			}
		}

		result.put("items", items);
		result.put("count", items.size());
		result.put("page", 0);

		return result;
	}

	private JSONObject SimChargeRecordToJSON(SimChargeRecord record) {
		JSONObject item = new JSONObject();
		item.put("id", record.getChargeId());
		item.put("price", record.getChargeAmount().toString());
		SimFlowPackageInfo packageInfo = simService.getSimFlowPackageInfoById(record.getFlowPackageId());
		item.put("name", packageInfo == null ? "" : packageInfo.getName());
		item.put("status", record.getChargeStatus() + "");
		item.put("created", record.getCreated() == null ? "" : record.getCreated().getTime());
		return item;
	}

	public JSONObject getOrderDetail(Long customerId, String id) throws CarsmartException {

		if (StringUtils.isBlank(id)) {
			throw new BadRequestException("400", "请输入订单号!");
		}
		JSONObject item = new JSONObject();
		SimChargeRecord record = simChargeRecordService.getChargeRecordById(Long.valueOf(id));
		if (record != null) {
			item = SimChargeRecordToJSON(record);
		}
		return item;
	}

	public void deleteOrder(Long customerId, String idStr) throws CarsmartException {
		if (StringUtils.isBlank(idStr)) {
			throw new BadRequestException("400", "请输入订单号!");
		}
		String[] idArray = idStr.split(",");
		for (String id : idArray) {
			simChargeRecordService.delete(Long.valueOf(id));
		}
	}

}
